<?php
declare (strict_types = 1);

namespace app\lib\response;

/**
 * 返回json封装
 */
class JSON
{
    const CODE_SUCCESS  = 200;
    const CODE_CLIENT_ERROR  = 400;
    const CODE_UNLOGIN_ERROR  = 401;
    const CODE_NO_PERMISSION_ERROR  = 403;
    const CODE_SERVER_ERROR  = 500;

    protected static $errorMsgs = [
        self::CODE_SUCCESS => '成功',
        self::CODE_CLIENT_ERROR => '失败',
        self::CODE_UNLOGIN_ERROR => '未登录或登录状态过期',
        self::CODE_NO_PERMISSION_ERROR => '没有权限',
        self::CODE_SERVER_ERROR => '服务器错误',
    ];

    public static function response(int $code,string $msg,?array $data){
        if(empty($msg) && array_key_exists($code,self::$errorMsgs)){
            $msg = self::$errorMsgs[$code];
        }
        return json([
            'code' => $code,
            'message' => $msg,
            'data' => $data,
        ]);
    }

    public static function success(string $msg = "",?array $data = null){
        return self::response(self::CODE_SUCCESS,$msg,$data);
    }

    public static function successData(array $data){
        return self::response(self::CODE_SUCCESS,"",$data);
    }

    public static function page(int $total,array $list){
        return self::response(self::CODE_SUCCESS,"",[
            'total' => $total,
            'list' => $list,
        ]);
    }

    public static function error(string $msg = "",int $code = self::CODE_CLIENT_ERROR){
        return self::response($code,$msg,null);
    }

}
